<template>
  <div id="warehouseList">
    <h1 class="page-title">仓库列表</h1>
    <!-- 表格 -->
    <el-table :data="tableData" border style="width: 100%;" class="custom-table">
      <el-table-column prop="stockId" label="编号" width="80" align="center"></el-table-column>
      <el-table-column prop="stockName" label="仓库名称" width="180" align="center"></el-table-column>
      <el-table-column prop="maxAmount" label="库存报警上限(件)" width="150" align="center"></el-table-column>
      <el-table-column prop="minAmount" label="库存报警下限(件)" width="150" align="center"></el-table-column>
      <el-table-column prop="maxCapacityAmount" label="最大存储量(件)" width="150" align="center"></el-table-column>
      <el-table-column label="(禁用/启用)" width="120" align="center">
        <template slot-scope="scope">
          <el-switch
              :value="scope.row.onOff === 1"
              @change="handleSwitchChange(scope.row)"
              active-color="#13ce66"
              inactive-color="#ff4949"
              class="custom-switch"
          ></el-switch>
          <span>{{ scope.row.onOff === 1 ? '启用' : '禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <!-- 仅当启用状态时显示修改按钮 -->
          <el-button
              v-if="scope.row.onOff === 1"
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
              class="el-icon-edit custom-edit-button"
          >
            修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px; text-align: right;"
        class="custom-pagination"
    ></el-pagination>

    <!-- 修改对话框 -->
    <el-dialog title="修改仓库信息" :visible.sync="editDialogVisible" class="custom-dialog">
      <el-form :model="editForm" label-width="120px" :rules="editRules" ref="editFormRef" class="custom-form">
        <el-form-item label="仓库名称" prop="stockName">
          <el-input v-model="editForm.stockName"></el-input>
        </el-form-item>
        <el-form-item label="库存报警上限" prop="maxAmount">
          <el-input v-model.number="editForm.maxAmount"></el-input>
        </el-form-item>
        <el-form-item label="库存报警下限" prop="minAmount">
          <el-input v-model.number="editForm.minAmount"></el-input>
        </el-form-item>
        <el-form-item label="最大存储量" prop="maxCapacityAmount">
          <el-input v-model.number="editForm.maxCapacityAmount"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
              :value="editForm.onOff === 1"
              @change="handleEditSwitchChange"
              active-color="#13ce66"
              inactive-color="#ff4949"
              class="custom-switch"
          ></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer custom-footer">
        <el-button @click="editDialogVisible = false" class="custom-cancel-button">取消</el-button>
        <el-button type="primary" @click="handleSaveEdit" class="custom-save-button">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "warehouseList",
  data() {
    return {
      searchName: '',
      searchType: '',
      tableData: [],
      currentPage: 1,
      pageSize: 7,
      total: 0,
      editDialogVisible: false,
      editForm: {
        stockId: null,
        stockName: '',
        productTypeList: '',
        maxAmount: null,
        minAmount: null,
        maxCapacityAmount: null,
        onOff: null
      },
      editRules: {
        stockName: [
          { required: true, message: '请输入仓库名称', trigger: 'blur' }
        ],
        productTypeList: [
          { required: true, message: '请输入仓库类型', trigger: 'blur' }
        ],
        maxAmount: [
          { required: true, message: '请输入库存报警上限', trigger: 'blur' },
          { type: 'number', message: '库存报警上限必须为数字', trigger: 'blur' }
        ],
        minAmount: [
          { required: true, message: '请输入库存报警下限', trigger: 'blur' },
          { type: 'number', message: '库存报警下限必须为数字', trigger: 'blur' }
        ],
        maxCapacityAmount: [
          { required: true, message: '请输入最大存储量', trigger: 'blur' },
          { type: 'number', message: '最大存储量必须为数字', trigger: 'blur' }
        ]
      },
      editFormRef: null,
      saveLoading: false // 新增保存操作的 loading 状态
    };
  },
  mounted() {
    this.fetchWarehouseList();
  },
  methods: {
    async fetchWarehouseList() {
      try {
        const response = await this.$axios.get('http://localhost:8090/stock/list', {
          params: {
            name: this.searchName,
            type: this.searchType,
            page: this.currentPage,
            size: this.pageSize
          }
        });
        this.tableData = response.data.records;
        this.total = response.data.total;
      } catch (error) {
        this.$message.error('获取仓库列表失败，请稍后重试');
        console.error('获取仓库列表失败:', error);
      }
    },
    handleSearch() {
      this.currentPage = 1;
      this.fetchWarehouseList();
    },
    handleReset() {
      this.searchName = '',
          this.searchType = '',
          this.currentPage = 1;
      this.fetchWarehouseList();
    },
    handleEdit(index, row) {
      this.editDialogVisible = true;
      this.editForm = {
        stockId: row.stockId,
        stockName: row.stockName,
        productTypeList: row.productTypeList,
        maxAmount: row.maxAmount,
        minAmount: row.minAmount,
        maxCapacityAmount: row.maxCapacityAmount,
        onOff: row.onOff
      };
    },
    async handleSaveEdit() {
      this.saveLoading = true;
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          // 创建一个新对象，用于存储除 onOff 之外的其他字段
          const updatedForm = {
            ...this.editForm,
            onOff: this.editForm.onOff // 保留原有的 onOff 值
          };
          try {
            const response = await this.$axios.put('http://localhost:8090/stock/update', updatedForm);
            if (response.data.success) {
              this.editDialogVisible = false;
              this.$message.success('修改仓库信息成功');
              await this.fetchWarehouseList(); // 使用 await 确保数据获取完成
            } else {
              this.$message.error(response.data.message);
            }
          } catch (error) {
            this.$message.error('修改仓库信息失败，请稍后重试');
            console.error('修改仓库信息失败:', error);
          } finally {
            this.saveLoading = false;
          }
        } else {
          this.$message.error('请填写完整并正确的信息');
          this.saveLoading = false;
        }
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchWarehouseList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchWarehouseList();
    },
    async handleSwitchChange(row) {
      console.log('当前行数据:', row); // 打印当前行数据，查看 onOff 值的变化
      row.onOff = row.onOff === 1 ? 0 : 1;
      try {
        const response = await this.$axios.put('http://localhost:8090/stock/update', row);
        if (response.data.success) {
          this.$message.success('状态修改成功');
        } else {
          this.$message.error(response.data.message);
          // 恢复原状态
          row.onOff = row.onOff === 1 ? 0 : 1;
        }
      } catch (error) {
        this.$message.error('状态修改失败，请稍后重试');
        // 恢复原状态
        row.onOff = row.onOff === 1 ? 0 : 1;
        console.error('状态修改失败:', error);
      }
    },
    handleEditSwitchChange(value) {
      console.log('Before change, editForm.onOff:', this.editForm.onOff);
      this.editForm.onOff = value ? 1 : 0;
      console.log('After change, editForm.onOff:', this.editForm.onOff);
    }
  }
};
</script>

<style scoped>
.demo-form-inline {
  margin-bottom: 20px;
}

.el-table {
  margin-top: 20px;  /* 调整表格上边距 */
}

.el-pagination {
  margin-top: 20px;  /* 调整分页组件的上边距 */
  text-align: right;  /* 分页组件内容居中 */
}

/* 新增：使表格内容居中 */
.el-table .cell {
  text-align: center; /* 使表格内容居中 */
}

/* 自定义表格样式 */
.custom-table {
  border-radius: 5px;  /* 添加圆角 */
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
  overflow: hidden; /* 防止表格边框溢出 */
}

/* 自定义开关样式 */
.custom-switch {
  width: 60px;  /* 调整宽度 */
  height: 30px;  /* 调整高度 */
}

/* 自定义编辑按钮样式 */
.custom-edit-button {
  background-color: #409eff;
  color: white;  /* 按钮文字颜色 */
  border: none;  /* 移除边框 */
  border-radius: 3px;  /* 圆角 */
  padding: 5px 10px;  /* 增加内边距 */
  cursor: pointer;  /* 添加鼠标指针样式 */
  transition: background-color 0.3s ease; /* 添加过渡效果 */
}

.custom-edit-button:hover {
  background-color: greenyellow;  /* 鼠标悬停时的背景颜色 */
}

/* 自定义分页样式 */
.custom-pagination {
  margin-top: 20px;  /* 调整分页组件的上边距 */
  text-align: right; /* 分页组件内容居中 */
  padding: 10px;  /* 增加内边距 */
  background-color: #f9f9f9;  /* 背景颜色 */
  border-radius: 5px;  /* 圆角 */
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1); /* 阴影效果 */
}

/* 自定义对话框样式 */
.custom-dialog {
  border-radius: 5px;  /* 圆角 */
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);  /* 阴影效果 */
}

/* 自定义表单样式 */
.custom-form {
  padding: 20px;  /* 增加内边距 */
}

/* 自定义对话框底部样式 */
.custom-footer {
  text-align: right;  /* 内容右对齐 */
  padding: 10px;  /* 增加内边距 */
  border-top: 1px solid #e4e7ed;  /* 顶部边框 */
}

/* 自定义取消按钮样式 */
.custom-cancel-button {
  background-color: #f4f4f4;  /* 背景颜色 */
  color: #666;  /* 文字颜色 */
  border: none;  /* 移除边框 */
  border-radius: 3px;  /* 圆角 */
  padding: 5px 10px;  /* 内边距 */
  cursor: pointer;  /* 鼠标指针样式 */
  transition: background-color 0.3s ease; /* 过渡效果 */
}

.custom-cancel-button:hover {
  background-color: #eaeaea;  /* 鼠标悬停时的背景颜色 */
}

/* 自定义保存按钮样式 */
.custom-save-button {
  background-color: #409eff;  /* 背景颜色 */
  color: white;  /* 文字颜色 */
  border: none;  /* 移除边框 */
  border-radius: 3px;  /* 圆角 */
  padding: 5px 10px;  /* 内边距 */
  cursor: pointer;  /* 鼠标指针样式 */
  transition: background-color 0.3s ease; /* 过渡效果 */
}

.custom-save-button:hover {
  background-color: #66b1ff;  /* 鼠标悬停时的背景颜色 */
}
</style>